##parameters=assessmentIdentity, actionIdentity=None, assignTo=None, comments=None, notify=False, exitURL=None, exitForm=False

form = context.REQUEST.form

from DateTime import DateTime

now = DateTime().strftime("%d %b %Y %H:%M")

msg = ""

#username = str( context.REQUEST.AUTHENTICATED_USER )
    
userProviderService = context.knowledgeengine_userproviderservice
#user = userProviderService.getUser( username )
user = userProviderService.getAuthenticatedUser()
             
if actionIdentity:
    action = context.getComponentByIdentity( actionIdentity )
else:
    action = None    

ass = context.knowledgeengine_assessmentstorageservice 
assessment = ass.loadAssessment( assessmentIdentity, userIdentity=user.getIdentity())
    
# Process embedded components 
msg += context.embedComponent_process( assessmentIdentity, form )

#logged = False
#if changelog:
    #ass.logWorkflowChange( assessment, action, comments, changelog )
    #logged = True
        
# Changing workflow states may remove the assessment from the users personal repository.
# Remember the current user so we can re-add later if needed.
#oldAuthor = context.getIPOwner( assessmentIdentity )

#oldState     = context.getIPWorkflowState( assessmentIdentity )

#newState = None

if assignTo:    
    
    previousUser = assessment.getResponsible()
    if assignTo != previousUser:    
        assessment.setResponsible( assignTo )
        ass.saveAssessment( assessment )    
    
        assignToUser = context.portal_membership.getMemberById( assignTo )
        if assignToUser:
            msg += "Assigning to user '%s'\n" % ( assignToUser.getProperty('fullname') or assignToUser.getId() )
        else:
            msg += "Assigning to user '%s'\n" % assignTo

logged = False

# First, trigger the action
if actionIdentity:
    
    if not action:
        raise "Unable to find action %s" % actionIdentity

    #if logged:
        #action.execute( assessment, user, workflowComments=' ' )
    #else:
    
    action.execute( assessment, user, workflowComments=comments )
    
    ass.saveAssessment(assessment)
    
    #newState = context.getIPWorkflowState( assessmentIdentity )
    
    msg += "Executing action %s\n" % `action.title_or_id()`
    
    # This is now triggered directly by the assessment action, no need to log here.
    #ass.logWorkflowChange( assessment, action, comments, msg )    
    logged = True
    
else:
    action = None
    if not msg: msg    = "(No Action)"
    

# If no previous action has triggered a workflog log hit, do so now
if not logged:
    ass.logWorkflowChange( assessment, None, comments, msg )        



if notify:
    
    notificationMode = context.getNotificationMode()
    dNotifyList = {}
  
    # Both Responsible and Participants mode will email the responsible person
    if notificationMode in ( "Responsible", "Participants" ):
        dNotifyList[ assessment.getResponsible() ] = True
        
    if notificationMode == "Participants":
        
        # Participants mode will email anyone that has contributed to this workflow, ever
        history = ass.getWorkflowHistory( assessmentIdentity )
        for item in history:
            dNotifyList[ item['userIdentity'] ] = True
            
        # As well as the creator
        dNotifyList[ assessment.getCreatedBy() ] = True
            
    # Get the final unique list of usernames to contact
    notifyList = dNotifyList.keys()
    
    getMemberById = context.portal_membership.getMemberById
    
    # Turn the list of usernames into a list of users (Filtering any blanks that popup)
    notifyMembers = filter(None, [ getMemberById( user_id ) for user_id in notifyList ])        
    
    # Get the email address for each of those users (Filterout out blanks)
    notifyEmails  = filter(None, [ user.getProperty( 'email' ).strip() for user in notifyMembers ]) 
                
    brain = dict(form)
    brain['msg'] = msg
    brain['url'] = context.absolute_url() + "/generate?assessmentIdentity=" + assessmentIdentity
    brain['portal_url'] = context.portal_url()
    brain['assessment'] = assessment
        
    email_message = context.workflow_notify_email_template( **brain )
        
    sender = context.portal_url.getPortalObject().email_from_address
               
    for email in notifyEmails:        
        context.MailHost.simple_send( email, sender, "Workflow Update - " + assessment.getName(), email_message )
        




    
redirect = context.REQUEST.RESPONSE.redirect
msg = "Workflow status updated"

if exitForm:
    url = exitURL
    if not '?' in url: url += "?"
    
    if form.get("isPopup"):
        return """
            <script> window.close(); </script>    
        """
    
    url += "&portal_status_message=%s" % ( msg )
    return redirect(url)
    
else:
    context.REQUEST.set('portal_status_message', msg)
    return context.WorkflowReport_report()    


